//
//  THWindowPriority.m
//  MengLiao
//
//  Created by xiuxin on 2022/7/15.
//  Copyright © 2022 BaseBusiness. All rights reserved.
//
#import "THWindowPriority.h"

@interface THWindowPriority()

@property (nonatomic) NSInteger priority;

@property (weak,nonatomic) UIView * view;

@property (nonatomic) BOOL replaceable;

@end

@implementation THWindowPriority

+ (THWindowPriority *)sharedInstance
{
    static id singleton = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        singleton = [self new];
    });
    return singleton;
}

+ (BOOL)requestPriority:(NSInteger)priority view:(UIView *)view replaceable:(BOOL)replaceable
{
    if ([[self sharedInstance] view] == view && [self viewIsVisible:view])
    {
        return NO;
    }
    if ([[self sharedInstance] checkPriority:priority])
    {
        [[self sharedInstance] releaseView];
        [self sharedInstance].priority = priority;
        [self sharedInstance].view = view;
        [self sharedInstance].replaceable = replaceable;
        return YES;
    }
    return NO;
}

+ (BOOL)requestPriority:(NSInteger)priority view:(UIView *)view
{
    return [self requestPriority:priority view:view replaceable:YES];
}

+ (void)releasePriority:(NSInteger)priority view:(UIView *)view
{
    if (view == [self sharedInstance].view && priority == [self sharedInstance].priority)
    {
        [self clean];
    }
}

+ (void)clean
{
    [[self sharedInstance] setView:nil];
    [[self sharedInstance] setPriority:0];
}

+ (UIView *)currentView
{
    return [self sharedInstance].view;
}

+ (NSInteger)currentPriority
{
    return [self sharedInstance].priority;
}

+ (BOOL)currentReplaceable
{
    return [self sharedInstance].replaceable;
}

+ (BOOL)checkPriority:(NSInteger)priority
{
    return [[self sharedInstance] checkPriority:priority];
}

- (BOOL)checkPriority:(NSInteger)priority
{
    if (![self.class viewIsVisible:self.view])
    {
        return YES;
    }
    else if (self.replaceable)
    {
        return priority >= self.priority;
    }
    return NO;
}

- (void)releaseView
{
    if ([self.view respondsToSelector:@selector(dismiss)])
    {
        [(UIView<HQWindowDismissProtocl> *)self.view dismiss];
    }
    else
    {
        [self.view removeFromSuperview];
    }
    self.view = nil;
    self.priority = 0;
}

+ (BOOL)viewIsVisible:(UIView *)view
{
     CGSize size = view.frame.size;
     return view.alpha > .02f && !view.isHidden && view.window != nil && size.width > 0 && size.height > 0 && CGRectIntersectsRect([UIScreen mainScreen].bounds,[view convertRect:view.bounds toView:view.window]);
}


@end
